# 从sklearn.datasets里导入新闻数据抓去器fetch_20newsgroups
from sklearn.datasets import fetch_20newsgroups
from sklearn.cross_validation import train_test_split

# 从sklearn.feature_extraction.text导入用于文本特征向量转换模块
from sklearn.feature_extraction.text import CountVectorizer
# 从sklearn.naive_bayes导入贝叶斯模型
from sklearn.naive_bayes import MultinomialNB

from sklearn.metrics import classification_report

# 从互联网下载数据
news = fetch_20newsgroups(subset='all')

# 随机采样25%的数据样本作为测试集
X_train, X_test, y_train, y_test = train_test_split(news.data, news.target, test_size=0.25, random_state=33)
# print(X_train)

# 转换文本特征向量
vec = CountVectorizer()

X_train = vec.fit_transform(X_train)
X_test = vec.transform(X_test)

# 使用默认配置初始化朴素贝叶斯模型
mnb = MultinomialNB()
# 利用训练数据对模型参数进行估计
mnb.fit(X_train, y_train)

# 对测试样本进行类别预测，结果存储在变量y_predict中
y_predict = mnb.predict(X_test)
# print(y_predict)

print('用模型自带的评估函数进行评估准确率',mnb.score(X_test, y_test))
# 打印详细的分类性能报告
print(classification_report(y_test, y_predict, target_names=news.target_names))